<template>
  <div class="grid_gadget_tempalte" :id="id" style="width:100%;height:100%">
    <Portal
      to="right-disable"
      v-loading="loading"
      :disabled="!queryModelDefaultSetting.showSetting"
      style="width:100%;height:100%"
    >
      <DashboardInterceptConsumer
        :gadgetId="id"
        shadow="never"
        class="aui-card--fill"
        @mouseenter="mouseenter(true)"
        @mouseleave="mouseenter(false)"
        style="width:100%;height: 100%;border:0">
        <el-card
          shadow="never"
          class="aui-card--fill content-card"
          :style="isHasData ? 'width:100%;height: 100%;border:0;overflow: visible;' : 'width:100%;height: 100%;border:0;overflow: hidden;'">
          <div style="width:100%;height:100%;overflow: hidden;">
            <div
              class="cardHeader"
              @mouseenter="mouseenter(true)"
              @mouseleave="mouseenter(false)"
              v-if="
                (widgetName && widgetName.trim().length > 0) ||
                (gadgetSetting.headerDescription &&
                  gadgetSetting.headerDescription.trim().length > 0)
              "
            >
              <GadgetTitle
                :gadgetSetting="gadgetSetting"
                :widgetName="widgetName"
              ></GadgetTitle>
              <div>
                <MoreMenu
                  :slicer="slicer"
                  :fitToHeight="fitToHeight"
                  :gadgetId="id"
                  :gadgetType="gadgetInfo.com"
                  @updateQuery="query"
                  :widgetName="widgetName"
                  :businessType="gadgetInfo.businessType"
                  :id="gadgetInfo.id"
                  @showQueryModel="showQueryModel"
                  @fullScreen="fullScreen"
                />
              </div>
            </div>
            <div class="control-section" style="margin: 10px 10px;height: calc(100% - 90px)">
              <!-- <el-button @click="devSetting">get setting</el-button> -->
              <div class="content-wrapper" style="width:100%;height:100%;">
                <el-table
                v-if="isHasData"
                        border
                        height="100%"
                        :cell-class-name="tableCellClassName"
                        :cell-style="handleCellStyle"
                        :data="comData(tableDataList)"
                        @cell-click="tableCellClick"
                        style="width: 100%;">

                        <el-table-column
                          :prop="gadgetSetting.rowDimesion"
                          >
                          <template slot-scope="scope">
                           {{ formatX[scope.$index][gadgetSetting.rowDimesion] }}
                         </template>

                        </el-table-column>
                        <el-table-column v-for="(data,index) in setColumn(tableDataList)" :key="data[gadgetSetting.columnDimesion]"
                          :prop="data.label"
                          :label="data.label"
                         >
                         <template slot="header">
                          {{ formatY[index] }}
                     
                         </template>
                         <template slot-scope="scope">
                           <component :is="`${findTableTemplateName('formatNumber')}`"
                                      :dataFrom="'Table'"
                                      :curData="dataList[scope.$index][data.label]"
                                      :curRow="scope.row"
                                      :column="data.data"
                                     
                                     ></component>
                         </template>
                        </el-table-column>
                    
                      </el-table>
                <Pagination v-if="isHasData&&gadgetSetting.allowPaging" @query="query" v-model="pageConfig"  ></Pagination>     
                <div v-if="!isHasData" class="gadget-no-newdata">
                  <div class="widgets-no-data">
                    <div :style="{ fontSize: fontSizeStr1 }">
                      {{ $t('custom.component.gadget.nodata') }}
                    </div>
                    <div class="widgets-tip">
                      <a
                        :href="widgetNoDataWiki"
                        :style="{ fontSize: fontSizeStr2 }"
                        target="black"
                        >{{ $t('custom.component.gadget.nodatatip') }}</a
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime
          v-if="currentTime"
          :currentTime="currentTime"
          :linkedDatasetList="linkedDatasetList"
          :errorStatus="errorStatus"
          @updateQuery="query()"
        ></Lastupdatetime>
      </DashboardInterceptConsumer>
    </Portal>
    <model
      :showSetting="queryModelDefaultSetting.showSetting"
      @queryModelClosed="queryModelClosed"
      @queryModelPreview="queryModelPreview"
      :dataInfo="queryModelDefaultSetting.dataInfo"
      :updateGadget="upgradeGadgetSetting"
    />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { getDrillthrough } from '@/utils/common'

import { v4 } from 'uuid'
import ExportOptionDialog from '@/components/export-option-dialog/dialog.vue'
export default {
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: {
    Lastupdatetime,
    model: () => import('@/components/gadget/query-model/query-model'),
    ExportOptionDialog
  },
  data() {
    return {
      currentTime: null,
      isGridInit: false,
      dataList: [],
      tableDataList: [],
      conditionFormat: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'tablegadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, {
            gadgetType: 'tablegadget'
          }).gadgetSetting
        }
      },
      widgetName: '',
      gadgetSetting: {},
      queryId: '',
      linkedDatasetList: [],
      uuid: v4(),
      exportOptionDialogVisible: false,
      tableDataFormatdataList:[]
    }
  },

  beforeCreate() {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created() {
    this.heightoffset = 5
    this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :
    this.pageFromType === 'report'
      ? this.gadgetInfo.h * this.rolHeight - this.heightoffset - 15
      : this.pageFrom === 'reportLayout'
      ? this.gadgetInfo.h * 20 - this.heightoffset - 15
      : this.gadgetInfo.h * 23 - this.heightoffset - 15
    Vue['_this'] = this
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  activated() {
    this.uuid = v4()
  },
  computed: {
    formatY() {
     return this._.uniqBy(this.tableDataFormatdataList,this.gadgetSetting.columnDimesion).map(i=>i[this.gadgetSetting.columnDimesion]).sort((a,b)=>(Number(a)-Number(b)))
    },
    formatX() {
     let yList = this._.uniqBy(JSON.parse(JSON.stringify(this.tableDataFormatdataList)),this.gadgetSetting.rowDimesion).sort((a,b)=>(Number(a[this.gadgetSetting.rowDimesion])-Number(b[this.gadgetSetting.rowDimesion])))
     let xList = this._.uniqBy(JSON.parse(JSON.stringify(this.tableDataFormatdataList)),this.gadgetSetting.columnDimesion)
     let keys =xList.map(item=>{
       return item[this.gadgetSetting.columnDimesion]
     })
     yList.forEach(item=>{
       keys.forEach(ii=>{
         let res = this.tableDataFormatdataList.find(i=>i[this.gadgetSetting.columnDimesion] === ii&&i[this.gadgetSetting.rowDimesion] === item[this.gadgetSetting.rowDimesion])
         item[ii] =res&&res[this.gadgetSetting.valueMeasure]? res[this.gadgetSetting.valueMeasure]:null

       })
     })
     return yList
    }
  },
  watch: {
    editMode(val) {
      if (!val) {
        this.saveGadgetSetting()
      } else {
      }
    }
  },
  methods: {

    setColumn(data) {
      let dataArr = this._.uniqBy(JSON.parse(JSON.stringify(data)),this.gadgetSetting.columnDimesion).map(i=>i[this.gadgetSetting.columnDimesion]).sort((a,b)=>(Number(a)-Number(b)))
      dataArr = dataArr.map(item=>{
        return {
          label: item,
          data: this.selectFields.find(i=>i.alias===this.gadgetSetting.valueMeasure) || {},
        }
      })

      return dataArr
    },
    comData(data) {
      let yList = this._.uniqBy(JSON.parse(JSON.stringify(data)),this.gadgetSetting.rowDimesion).sort((a,b)=>(Number(a[this.gadgetSetting.rowDimesion])-Number(b[this.gadgetSetting.rowDimesion])))
     
      let xList = this._.uniqBy(JSON.parse(JSON.stringify(data)),this.gadgetSetting.columnDimesion)
      let keys =xList.map(item=>{
        return item[this.gadgetSetting.columnDimesion]
      })
      yList.forEach(item=>{
        keys.forEach(ii=>{
          let res = data.find(i=>i[this.gadgetSetting.columnDimesion] === ii&&i[this.gadgetSetting.rowDimesion] === item[this.gadgetSetting.rowDimesion])
      
          item[ii] =res&&res[this.gadgetSetting.valueMeasure]? res[this.gadgetSetting.valueMeasure]:null
          

        })
      })
      this.dataList = yList
      return yList

    },
    
    tableCellClick (rowData, columnData) {
      if(columnData.property === this.gadgetSetting.rowDimesion) {
        return
      }

      rowData[this.gadgetSetting.columnDimesion] = columnData.label
      this.queryId = this.selectFields.find(item => item.bind === this.gadgetSetting.rowDimesion) ? this.selectFields.find(item => item.bind === this.gadgetSetting.rowDimesion).queryId : ''
      let sql = ''
      let val1 = rowData[this.gadgetSetting.valueMeasure] == null? 'is null':`${rowData[this.gadgetSetting.valueMeasure]}`
      let val2 = rowData[this.gadgetSetting.rowDimesion] == null? 'is null':`${rowData[this.gadgetSetting.rowDimesion]}`
      let val3 = rowData[this.gadgetSetting.columnDimesion] == null? 'is null':`${rowData[this.gadgetSetting.columnDimesion]}`

      let sqlArr = []
      const rowobj = {
        selectField: this.selectFields.find(item => item.bind === this.gadgetSetting.rowDimesion) || {},
        value: val2,
        timezoneId: this.$store.state.user.timezoneId
      }
      const colobj = {
        selectField:this.selectFields.find(item => item.bind === this.gadgetSetting.columnDimesion),
        value: val3,
        timezoneId: this.$store.state.user.timezoneId
      }
      sqlArr.push(rowobj,colobj)  

      // sql = `"${this.findField(this.gadgetSetting.rowDimesion)}" ${val2} and "${this.findField(this.gadgetSetting.columnDimesion)}" ${val3}`
      if (sqlArr.length===2) {
        this.findOriginData(sqlArr)
      } else {
        return
      }
      
    },
    findField(val) {
      let res = this.selectFields.find(i=>i.bind === val)
      if(res) {
        return res.field
      }
    },

    tableCellClassName ({ row, column,rowIndex }) {
      if(column.property === this.gadgetSetting.rowDimesion) {
        return
      }
      try {
        return 'cursor-pointer'
      } catch (error) {

      }
    },
    queryModelClosed() {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    queryModelPreview() {
      this.query()
    },
    showQueryModel() {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized(i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight =
        this.pageFromType === 'report'
          ? newH * this.rolHeight - this.heightoffset - 15
          : newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
    },
    async query(e) {
      let isPaging = false
      try {
        if(!this.$route.path.includes('/publicReportPdf')){
          if (this.isQueryModel && this.isQueryModel()) {
            isPaging = this.dataInfo.gadgetSetting.allowPaging
          } else {
            const { gadgetSetting } = await this.getWidgetInfo(this.id)
            isPaging = gadgetSetting.allowPaging
          }
        }
      } catch (error) {

      }
      if (e !== 'auto') {
        this.loading = true
        this._.merge(
          this.gadgetSetting,
          this.queryModelDefaultSetting.dataInfo.gadgetSetting
        )
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (
        tempObj['name'] &&
        this.slicer['name'] &&
        tempObj['name'] === this.slicer['name']
      )
        delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      const pageSize=this.$route.path.includes('/publicReportPdf')?{
        size:350,
        current:1
      }:{}
      var param = {
        ...pageSize,
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      if(this.$route.path !== '/publicReportPdf' && isPaging) {
        param.current = this.pageConfig.current
        param.size = 250
      }
      _self.$interface.reports
        .getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.verifyHasData(res)
          if (res.config) {
            _self.gadgetSetting = Object.assign(
              {},
              _self._.merge(_self.gadgetSetting, res.config)
            )
          }
          if (res.name) {
            _self.widgetName = res.name
          } else if (this.wName) {
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          _self.selectFields = res.selectFields
          _self.linkedDatasetList = res.datasetSync
          _self.conditionFormat = res.conditionFormat || []
          if (res.data) {
            try {
              if(res.data.records) {
                this.pageConfig.total = res.data.total
                this.pageConfig.gadgetType =this.wgadgettype
                this.pageConfig.pageSize =res.data.size
                res.data = res.data.records || []
              }
            } catch (error) {
              
            }
            _self.tableDataFormatdataList = _self.formatData(JSON.parse(JSON.stringify(res.data)), res.selectFields, 'tablegadget')
            _self.tableDataList = res.data
        }
       
          _self.uuid = v4()
          _self.isGridInit = false
        })
        .catch(error => {
          if (this.wName) {
            this.widgetName = this.wName
          }
          this.isHasData = false
          _self.loading = false
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        })
        .finally(() => {
          this.currentTime = new Date()
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    handleCellStyle (args) {
      try {
        let rowIndex
        let columnIndex
        let color
        let bgc
        var res = this.conditionFormat
        if (args.row) {
          res.forEach(it => {
            if (it) {
              let str = ''
              it.dataForm.filters.rules.forEach(ii => {
                if (ii.opt === 'is null'  ) {
                   ii.value = 'is null'
                   ii.opt = '=='
                }
                let val
                val = args.row[args.column.property] ===null ? 'is null' : args.row[args.column.property] ? args.row[args.column.property].toString() : ''
                
                if (ii.opt === '==' || ii.opt === '!=') {
                  if (!str) {
                    str += `("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& ("${(val).toString()}"  ${ii.opt}   "${(ii.value).toString()}")`
                    } else {
                      str += `|| ("${(val).toString()}"   ${ii.opt}   "${(ii.value).toString()}")`
                    }
                  }
                } else {
                  if (!str) {
                    str += (Number(val) + ii.opt + Number(ii.value))
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                    } else {
                      str += `|| (${Number(val)}   ${ii.opt}   ${Number(ii.value)})`
                    }
                  }
                }
              })
              let res1 = eval(`${str}`)
              if (res1) {
                if (it.entireRow !== 'row') {
                  rowIndex = args.rowIndex
                  columnIndex = args.columnIndex
                  color = it.textColor
                  if (it.formatRadio === 'color' ) {
                    bgc = it.backgroundColor
                  }
                  if (it.formatRadio === 'icon') {
                    args.row[args.column.property] = it.icon
                  }
                }
              }
            }
          })
          if (args.rowIndex === rowIndex&&columnIndex === args.columnIndex) {
            return `backgroundColor: ${bgc};color:${color};`
          }
        }

      } catch (error) {
        console.log(error);
      }

    },
    destroyed() {
      delete Vue['_this']
    },
    remove() {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    },
    closeExportOptionDialog() {
      this.exportOptionDialogVisible = false
    },
  }
}
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.grid_gadget_tempalte ::v-deep.e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.el-card ::v-deep .el-card__body {
  width: 100%;
  height: 100%;
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  overflow-y: auto;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
</style>
